package com.ias.agdis_r.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;
import android.content.Intent;

import com.ias.agdis_r.R;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.util.sdcard.WriteLog;

public class TestUtil {

	public final static int TAG_0 = 0;   //未知（死机、扣电池、没电自动关机）,正常启动
	public final static int TAG_1 = 1;   //网络跳变
	public final static int TAG_2 = 2;   //应用系统被重启
	public final static int TAG_3 = 3;  //设备被关机
	
	//心跳消息中的TAG标签
	public final static String TAG ="TAG";
	//心跳消息中的本次重连成功的时间标签
	public final static String CCT ="CCT";
	//上次连接失效时间标签
	public final static String LCT ="LCT";
	//本机地址:端口
	public final static String LPP ="LPP";
	//附加信息
	public final static String TXT ="TXT";
	//WROCS设定的最大CPU,超过将会KILL掉程序
	public final static double MAX_WROCS_CPU_USAGE = 0.6;
	//其它程序的最大CPU值,超过将会重启设备
	public final static double MAX_PROCESS_CPU_USAGE = 0.6;
	//CPU信息(包含系统CPU和WROCS的CPU)
	public static String cpu_info ="";
	//占用最大的CPU信息
	public static String cpu_max_process_info ="";
	//Wrocs CPU信息
	public static String cpu_wrocs_info ="";
	//SGOC发送CPU信息时间间隔
	public static int  send_cpu_interval = 6;
	//SGOC发送计数 
	public static int  send_sgoc_count = 6;
	
	//上传UP_AKANSWER 
	public final static String UP_AKANSWER = "00"; 
	
	public static float PRIVATE_RSSI = -999;
	public static float PRIVATE_CINR = -999;
	public static int  cpu_wrocs_beyound_count = 0;

	private static Context context = DataBaseManager.getInstance().getContext();
	/**
	 * 执行SHELL命令
	 * @param cmd
	 * @return
	 */
	public static String do_shell(String cmd) {  
       String result = "";  
       try {  
	           Process p = Runtime.getRuntime().exec(cmd);  
	           BufferedReader in = new BufferedReader(  
	                               new InputStreamReader(p.getInputStream()));  
	           String line = null;  
	            while ((line = in.readLine()) != null) {  
	            	result += line + "/n";                 
	           }  
       	} catch (IOException e) {  
        // TODO Auto-generated catch block  
            e.printStackTrace();  
       }  
        return result;       
    }  
	
	/**
	 * 获取CPU信息
	 * @param cmd
	 * @return
	 */
	public static void getCpuInfo()
	{
			String resultlist = TestUtil.do_shell("top -n 1 -m 10");
			String[] results = resultlist.split("/n");
			//清空CPU信息
			TestUtil.cpu_info = "";
			TestUtil.cpu_max_process_info = "";
			//读取数据,
			//String result:results
			for(int i=0;i<results.length;i++)
			{
				//totalInfo还没有赋值
				if(S.isEmpty(TestUtil.cpu_info))
				{
					TestUtil.cpu_info =results[i];			
				}
				//如果未读取到最大的非WROCS程序的CPU,记录CPU信息
				else if(S.isEmpty(TestUtil.cpu_max_process_info)&&results[i].indexOf("%")>-1&&results[i].indexOf("CPU%")==-1&&results[i].indexOf("com.corget")==-1)
				{
					TestUtil.cpu_max_process_info  = results[i];
				}
				//如果此行信息是WROCS的CPU信息
				else if(results[i].indexOf("com.corget")>-1)
				 {
						TestUtil.cpu_wrocs_info = results[i];
					 	TestUtil.cpu_info =S.contact(TestUtil.cpu_info,"|",results[i]);
				 }
			}
			if(S.isNotEmpty(cpu_info))
			{
				TestUtil.cpu_info = TestUtil.cpu_info.replaceAll(",", "");
			}
			System.out.println("TestUtil.cpu_info:"+TestUtil.cpu_info);
			
			//如果WROCS的CPU超过最大的设定值,杀掉线程
			if(!checkAppCpu(TestUtil.cpu_wrocs_info,true))
			{
				WriteLog.getInstance().writeLog(context.getString(R.string.TU_1)+MAX_WROCS_CPU_USAGE+context.getString(R.string.TU_2));
				//杀掉Wrocs线程.
				android.os.Process.killProcess(android.os.Process.myPid()) ;
			}
			//如果其它应用的CPU超过最大的设定值,重启设备
			if(!checkAppCpu(TestUtil.cpu_max_process_info,false))
			{
				WriteLog.getInstance().writeLog(context.getString(R.string.TU_3)+MAX_PROCESS_CPU_USAGE+context.getString(R.string.TU_4));
				//发送重新启动设备的广播
				Intent i = new Intent("com.android.internal.REBOOT");
				DataBaseManager.getInstance().getContext().sendBroadcast(i);
			}
	}
	
	/**
	 * 检测WROCS,CPU是否超出设定大小
	 * @param cmd
	 * @return
	 */
	public static boolean checkAppCpu(String cpuInfo,boolean isWrocs)
	{
		if(S.isEmpty(cpuInfo))
		{
			return true;
		}
		int index =  cpuInfo.indexOf("%");
		 if(index>=0)
		{
			 String scpuUsage  = cpuInfo.substring(index-2,index);
			try {
				double dcpuUsage  = Double.parseDouble(scpuUsage.trim())*0.01;
				if(isWrocs)
				{
					if(dcpuUsage >=MAX_WROCS_CPU_USAGE )
					{
						cpu_wrocs_beyound_count ++;
						WriteLog.getInstance().writeLog(context.getString(R.string.TU_5)+cpuInfo);
						if(cpu_wrocs_beyound_count>=3)
						{
							WriteLog.getInstance().writeLog(context.getString(R.string.TU_6)+cpu_wrocs_beyound_count);
							return  false;
						}
						else
						{
							return true;
						}
					}
					else
					{ 
						cpu_wrocs_beyound_count =0 ;
						return true;
					}
				}
				else if(!isWrocs&&dcpuUsage>=MAX_PROCESS_CPU_USAGE)
				{
					WriteLog.getInstance().writeLog(context.getString(R.string.TU_7)+cpuInfo);
					return false;
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return true;
	}
}
